package com.example.chamberlainserver.controller;

import com.example.chamberlainserver.Entry.AdjustmentLog;
import com.example.chamberlainserver.Service.AdjustmentLogService;
import com.example.chamberlainserver.Vo.Response.ApiResponse;
import com.example.chamberlainserver.dto.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 调整日志控制器
 */
@RestController
@RequestMapping("/schedule/adjustments")
public class AdjustmentLogController {

    @Autowired
    private AdjustmentLogService adjustmentLogService;

    /**
     * 添加调整日志
     */
    @PostMapping("/add")
    @PreAuthorize("hasRole('COUNSELOR') or hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<Void>> addAdjustmentLog(@RequestBody AdjustmentLog adjustmentLog) {
        try {
            // 设置调整人
            String username = SecurityContextHolder.getContext().getAuthentication().getName();
            // 这里需要根据username获取userId，暂时设置为1
            adjustmentLog.setAdjustedBy(1);
            
            boolean success = adjustmentLogService.addAdjustmentLog(adjustmentLog);
            
            if (success) {
                return ResponseEntity.ok(ApiResponse.success("添加调整日志成功", null));
            } else {
                return ResponseEntity.ok(ApiResponse.error("添加调整日志失败"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("添加调整日志失败: " + e.getMessage()));
        }
    }

    /**
     * 根据ID获取调整日志
     */
    @GetMapping("/get/{id}")
    @PreAuthorize("hasRole('COUNSELOR') or hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<AdjustmentLog>> getAdjustmentLogById(@PathVariable String id) {
        try {
            AdjustmentLog adjustmentLog = adjustmentLogService.getAdjustmentLogById(id);
            
            if (adjustmentLog != null) {
                return ResponseEntity.ok(ApiResponse.success("获取调整日志成功", adjustmentLog));
            } else {
                return ResponseEntity.ok(ApiResponse.error(404, "调整日志不存在"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取调整日志失败: " + e.getMessage()));
        }
    }

    /**
     * 根据排班分配ID获取调整日志列表
     */
    @GetMapping("/assignment/{assignmentId}")
    @PreAuthorize("hasRole('COUNSELOR') or hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<List<AdjustmentLog>>> getAdjustmentLogsByAssignmentId(@PathVariable String assignmentId) {
        try {
            List<AdjustmentLog> adjustmentLogs = adjustmentLogService.getAdjustmentLogsByAssignmentId(assignmentId);
            return ResponseEntity.ok(ApiResponse.success("获取排班分配调整日志列表成功", adjustmentLogs));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取排班分配调整日志列表失败: " + e.getMessage()));
        }
    }

    /**
     * 根据调整类型获取调整日志列表
     */
    @GetMapping("/type/{adjustmentType}")
    @PreAuthorize("hasRole('COUNSELOR') or hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<List<AdjustmentLog>>> getAdjustmentLogsByType(@PathVariable String adjustmentType) {
        try {
            List<AdjustmentLog> adjustmentLogs = adjustmentLogService.getAdjustmentLogsByType(adjustmentType);
            return ResponseEntity.ok(ApiResponse.success("获取调整类型日志列表成功", adjustmentLogs));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取调整类型日志列表失败: " + e.getMessage()));
        }
    }

    /**
     * 根据调整人获取调整日志列表
     */
    @GetMapping("/adjuster/{adjustedBy}")
    @PreAuthorize("hasRole('COUNSELOR') or hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<List<AdjustmentLog>>> getAdjustmentLogsByAdjustedBy(@PathVariable Integer adjustedBy) {
        try {
            List<AdjustmentLog> adjustmentLogs = adjustmentLogService.getAdjustmentLogsByAdjustedBy(adjustedBy);
            return ResponseEntity.ok(ApiResponse.success("获取调整人日志列表成功", adjustmentLogs));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取调整人日志列表失败: " + e.getMessage()));
        }
    }

    /**
     * 获取所有调整日志
     */
    @GetMapping("/all")
    @PreAuthorize("hasRole('COUNSELOR') or hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<List<AdjustmentLog>>> getAllAdjustmentLogs() {
        try {
            List<AdjustmentLog> adjustmentLogs = adjustmentLogService.getAllAdjustmentLogs();
            return ResponseEntity.ok(ApiResponse.success("获取所有调整日志列表成功", adjustmentLogs));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取所有调整日志列表失败: " + e.getMessage()));
        }
    }

    /**
     * 删除调整日志
     */
    @DeleteMapping("/delete/{id}")
    @PreAuthorize("hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<Void>> deleteAdjustmentLog(@PathVariable String id) {
        try {
            boolean success = adjustmentLogService.deleteAdjustmentLog(id);
            
            if (success) {
                return ResponseEntity.ok(ApiResponse.success("删除调整日志成功", null));
            } else {
                return ResponseEntity.ok(ApiResponse.error("删除调整日志失败"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("删除调整日志失败: " + e.getMessage()));
        }
    }

    /**
     * 根据排班分配ID删除调整日志
     */
    @DeleteMapping("/assignment/{assignmentId}")
    @PreAuthorize("hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<Void>> deleteAdjustmentLogsByAssignmentId(@PathVariable String assignmentId) {
        try {
            boolean success = adjustmentLogService.deleteAdjustmentLogsByAssignmentId(assignmentId);
            
            if (success) {
                return ResponseEntity.ok(ApiResponse.success("删除排班分配调整日志成功", null));
            } else {
                return ResponseEntity.ok(ApiResponse.error("删除排班分配调整日志失败"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("删除排班分配调整日志失败: " + e.getMessage()));
        }
    }

    /**
     * 分页查询调整日志列表
     */
    @GetMapping("/pagedList")
    @PreAuthorize("hasRole('COUNSELOR') or hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<PageResult<AdjustmentLog>>> getPagedAdjustmentLogList(
            @RequestParam(value = "current", required = false, defaultValue = "1") Integer current,
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,
            @RequestParam(value = "assignmentId", required = false) String assignmentId,
            @RequestParam(value = "adjustmentType", required = false) String adjustmentType,
            @RequestParam(value = "adjustedBy", required = false) Integer adjustedBy) {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("current", current);
            params.put("pageSize", pageSize);
            params.put("offset", (current - 1) * pageSize);
            
            if (assignmentId != null && !assignmentId.trim().isEmpty()) {
                params.put("assignmentId", assignmentId.trim());
            }
            if (adjustmentType != null && !adjustmentType.trim().isEmpty()) {
                params.put("adjustmentType", adjustmentType.trim());
            }
            if (adjustedBy != null) {
                params.put("adjustedBy", adjustedBy);
            }
            
            PageResult<AdjustmentLog> pageResult = adjustmentLogService.getPagedAdjustmentLogList(params);
            return ResponseEntity.ok(ApiResponse.success("获取调整日志列表成功", pageResult));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取调整日志列表失败: " + e.getMessage()));
        }
    }

    /**
     * 记录排班调整日志
     */
    @PostMapping("/log")
    @PreAuthorize("hasRole('COUNSELOR') or hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<Void>> logScheduleAdjustment(
            @RequestParam String assignmentId,
            @RequestParam String adjustmentType,
            @RequestParam(required = false) String reason,
            @RequestParam(required = false) String oldValue,
            @RequestParam(required = false) String newValue) {
        try {
            // 设置调整人
            String username = SecurityContextHolder.getContext().getAuthentication().getName();
            // 这里需要根据username获取userId，暂时设置为1
            Integer adjustedBy = 1;
            
            boolean success = adjustmentLogService.logScheduleAdjustment(
                    assignmentId, adjustmentType, reason, oldValue, newValue, adjustedBy);
            
            if (success) {
                return ResponseEntity.ok(ApiResponse.success("记录排班调整日志成功", null));
            } else {
                return ResponseEntity.ok(ApiResponse.error("记录排班调整日志失败"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("记录排班调整日志失败: " + e.getMessage()));
        }
    }
}